<template>
  <div class="line-sync-test">
    <h2>线条同步测试</h2>
    
    <div class="controls">
      <el-button @click="connect" :disabled="isConnected" type="primary">连接</el-button>
      <el-button @click="disconnect" :disabled="!isConnected" type="danger">断开</el-button>
      <el-button @click="joinRoom" :disabled="!isConnected" type="success">加入房间</el-button>
      <el-button @click="clearCanvas" type="info">清空画布</el-button>
    </div>
    
    <div class="canvas-container">
      <canvas
        ref="canvasRef"
        width="800"
        height="600"
        class="paint-canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
      ></canvas>
    </div>
    
    <div class="info">
      <p>连接状态: {{ isConnected ? '已连接' : '未连接' }}</p>
      <p>房间: {{ roomId }}</p>
      <p>玩家ID: {{ playerId }}</p>
      <p>发送: {{ sentCount }} | 接收: {{ receivedCount }}</p>
    </div>
    
    <div class="log">
      <h3>日志</h3>
      <div class="log-content">
        <div v-for="log in logs.slice(-5)" :key="log.id" class="log-item">
          {{ log.time }}: {{ log.message }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { createSignalRService } from '@/services/socketService'

const isConnected = ref(false)
const roomId = ref('line-test-001')
const playerId = ref('player-' + Math.random().toString(36).substr(2, 9))
const sentCount = ref(0)
const receivedCount = ref(0)
const logs = ref([])

const canvasRef = ref(null)
const ctx = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)

const signalRService = createSignalRService({})

function addLog(message) {
  logs.value.push({
    id: Date.now(),
    time: new Date().toLocaleTimeString(),
    message
  })
  if (logs.value.length > 20) logs.value.shift()
}

async function connect() {
  try {
    await signalRService.connect()
    isConnected.value = true
    addLog('连接成功')
  } catch (error) {
    addLog('连接失败: ' + error.message)
  }
}

async function disconnect() {
  try {
    await signalRService.disconnect()
    isConnected.value = false
    addLog('已断开')
  } catch (error) {
    addLog('断开失败: ' + error.message)
  }
}

async function joinRoom() {
  try {
    await signalRService.joinRoom(roomId.value, playerId.value, '测试玩家', '#ff0000')
    addLog('已加入房间')
  } catch (error) {
    addLog('加入房间失败: ' + error.message)
  }
}

function clearCanvas() {
  if (!ctx.value) return
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, 800, 600)
  addLog('画布已清空')
}

function startDrawing(event) {
  isDrawing.value = true
  const rect = canvasRef.value.getBoundingClientRect()
  lastX.value = event.clientX - rect.left
  lastY.value = event.clientY - rect.top
}

function draw(event) {
  if (!isDrawing.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  // 绘制
  ctx.value.strokeStyle = '#ff0000'
  ctx.value.lineWidth = 3
  ctx.value.lineCap = 'round'
  ctx.value.beginPath()
  ctx.value.moveTo(lastX.value, lastY.value)
  ctx.value.lineTo(x, y)
  ctx.value.stroke()
  
  // 立即发送
  const paintData = {
    x: Math.round(x),
    y: Math.round(y),
    color: '#ff0000',
    brushSize: 3,
    tool: 'brush',
    fromX: Math.round(lastX.value),
    fromY: Math.round(lastY.value)
  }
  
  try {
    signalRService.sendPaintActionWithData(roomId.value, playerId.value, paintData)
    sentCount.value++
  } catch (error) {
    console.error('发送失败:', error)
  }
  
  lastX.value = x
  lastY.value = y
}

function stopDrawing() {
  isDrawing.value = false
}

function handlePaintActionReceived(paintData) {
  receivedCount.value++
  
  if (!ctx.value) return
  
  const { x, y, tool, color, brushSize, fromX, fromY } = paintData
  
  if (tool === 'brush' && fromX !== undefined && fromY !== undefined) {
    ctx.value.strokeStyle = color
    ctx.value.lineWidth = brushSize
    ctx.value.lineCap = 'round'
    ctx.value.beginPath()
    ctx.value.moveTo(fromX, fromY)
    ctx.value.lineTo(x, y)
    ctx.value.stroke()
    addLog(`绘制线条: (${fromX},${fromY}) -> (${x},${y})`)
  }
}

onMounted(() => {
  const canvas = canvasRef.value
  if (canvas) {
    ctx.value = canvas.getContext('2d')
    ctx.value.fillStyle = '#ffffff'
    ctx.value.fillRect(0, 0, 800, 600)
  }
  
  signalRService.on('PaintActionReceived', handlePaintActionReceived)
  addLog('页面已加载')
})

onUnmounted(() => {
  signalRService.off('PaintActionReceived')
})
</script>

<style scoped>
.line-sync-test {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.canvas-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.paint-canvas {
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: crosshair;
  background: white;
}

.info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info p {
  margin: 0;
  font-size: 14px;
}

.log {
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.log h3 {
  margin: 0;
  padding: 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.log-content {
  height: 200px;
  overflow-y: auto;
  padding: 10px;
}

.log-item {
  font-size: 12px;
  margin-bottom: 5px;
  padding: 5px;
  background: #f0f0f0;
  border-radius: 4px;
}
</style>
